package cn.ctwing.ws.client;

import cn.ctwing.ws.client.api.IAuth;
import cn.ctwing.ws.client.api.IWSCallback;
import cn.ctwing.ws.client.impl.WSAuth;
import cn.ctwing.ws.client.impl.WSChannel;

public class WSClient {
	private String appKey;
	private String appSecret;
	private String host;
	private String token;
	private int channels=2;
	private IWSCallback callback;
	private IAuth auth = new WSAuth();
	/**
	 * 最长的存活时间
	 */
	private long maxConnectTime=0;
	
	public WSClient() {}
	
	
	public String getUri() {
		String uri =null;
		if(token!=null){
			uri=host+"/"+appKey+"/"+token;
		}else{
			uri=auth.genWsURI(host, appKey, appSecret);
		}
		  
		 if(!uri.startsWith("ws")) {
			 uri="ws://"+uri;
		 }
		return uri;
	}
	public WSClient  run() {
		System.out.println("启动客户端");
		for(int i=0;i<channels;i++) {
			new WSChannel(this).connect();
		}
		return this;
	}
	
	public WSClient setAppKey(String appKey) {
		this.appKey=appKey;
		return this;
	}

	public WSClient setAppSecret(String appSecret) {
		this.appSecret = appSecret;
		return this;
	}


	public WSClient setHost(String host) {
		this.host = host;
		return this;
	}


	/**
	 * 设置通道数
	 * @param channels
	 * @return
	 */
	public WSClient setChannels(int channels) {
		this.channels = channels;
		return this;
	}


	/**
	 * 
	 * @param callback
	 * @return
	 */
	public WSClient onMessage(IWSCallback callback) {
		this.callback = callback;
		return this;
	}


	public long getMaxConnectTime() {
		return maxConnectTime;
	}


	public WSClient setMaxConnectTime(long maxConnectTime) {
		this.maxConnectTime = maxConnectTime;
		return this;
	}

	public WSClient setToken(String token) {
		this.token = token;
		return this;
	}


	public IWSCallback getCallback() {
		return callback;
	}
}
